<?php


class IssueController extends Controller
{
  /**
   * 发表问题
   */
  public function actionPost()
  {
    $this->checkUserLogin(1, false);
    if (Yii::app()->request->isPostRequest) {
      $result = IssueService::instance()->post($this->filter($_POST));
      if ($result === true) {
        $this->success('发布成功!', Yii::app()->createUrl('issue/view', array('id' => Issue::$db->lastInsertID)));
      } else {
        $this->error($this->getError($result), 200);
      }
    } else {
      $this->render('/site/issue/post');
    }
  }

  /**
   * 查看问题
   * @param int $id
   */
  public function actionView($id = 0)
  {
    $issue = IssueService::instance()->getIssue($id, true);
    $data = IssueService::instance()->getReplyList($id, true, 10);
    if(empty($issue)){
      $this->error('问题不存在!',404);
    }
    $this->render('/site/issue/view', array(
        'issue' => $issue,
        'data' => $data
    ));
  }

  /**
   * 回答问题
   */
  public function actionReply()
  {
    if(Yii::app()->user->isGuest){
      $this->error('请登录!',200);
    }
    if (Yii::app()->request->isPostRequest) {
      $data = $this->filter($_POST);
      $result = IssueService::instance()->reply($data);
      if ($result === true) {
        $this->success('回答成功!', Yii::app()->createUrl('issue/view', array('id' => $data['issue_id'])));
      } else {
        $this->error($this->getError($result), 200);
      }
    } else {
      $this->error('非法访问!', 400);
    }
  }

  /**
   * 采纳问题
   * @param int $issue_id
   * @param int $reply_id
   */
  public function actionAccept($issue_id = 0, $reply_id = 0)
  {
    $this->checkUserLogin(1, false);
    $result = IssueService::instance()->accept($issue_id, $reply_id);
    if ($result === true) {
      $this->success('采纳成功!');
    } else {
      $this->error($this->getError($result), 200);
    }
  }

  /**
   * 问题列表
   * @param string $keywords
   */
  public function actionList($keywords = '')
  {
    $data = IssueService::instance()->getList(10,true,0,$keywords);
    $this->render('/site/issue/list', array(
        'data' => $data
    ));
  }
} 